class Solution
{
public:
    int maxSubarraySumCircular(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> dp(n + 1);
        auto f = dp;
        int ret = INT_MIN;
        int sum = accumulate(nums.begin(), nums.end(), 0);
        for (int i = 1; i <= n; i++)
        {
            dp[i] = max(dp[i - 1] + nums[i - 1], nums[i - 1]);
            ret = max(ret, dp[i]);
        }
        int add = INT_MAX;
        for (int i = 1; i <= n; i++)
        {
            f[i] = min(f[i - 1] + nums[i - 1], nums[i - 1]);
            add = min(add, f[i]);
        }
        return sum == add ? ret : max(ret, sum - add);
    }
};